<template>
  <div class="position">
    <div class="header">
      <div class="header-1">
        <div class="header-1-1">
          <div class="tou"></div>
          <span>查询条件</span>
        </div>
      </div>
      <el-form style="margin-left: 20px" size="mini" :inline="true" :data="Queryrole" :model="Queryrole"
        class="demo-form-inline">
        <el-form-item label="角色名称">
          <el-input v-model="Queryrole.positionName" placeholder="角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="Queryrole.positionDesc" placeholder="角色描述"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button style="width: 80px" type="primary" @click="seachBtn">查询
          </el-button>
          <el-button type="primary" @click="clear" style="width: 80px;">重置
          </el-button>
        </el-form-item>
      </el-form>
      <div class="hackhome"></div>
      <!-- 角色列表 -->
      <div class="header-1">
        <div class="tuo">
          <div class="tuo-1">
            <div class="tuo-2"></div>
            <span>角色列表</span>
          </div>
          <div class="tuo-3">
            <el-button type="primary" style=" color: #fff; width: 110px" size="mini" @click="newrole = true">新增
            </el-button>
          </div>
        </div>
        <!-- 角色列表内容 Therolelist-->
        <div class="table">
          <el-table border size="mini" ref="multipleTable" :data="Therolelist" :header-cell-style="{
              color: '#fff',
              background: '#6090EC',
              fontSize: '11px',
              fontWeight: 'normal',
            }" row-key="deptId" :tree-props="{ children: 'children' }">
            <el-table-column prop="roleName" label="角色名称" width="120">
            </el-table-column>
            <el-table-column label="角色状态" width="90">
              <!-- {{enableStart}} -->
              <template slot-scope="scope">
                {{scope.row.roleStatus=='yes'?'正常' :'停用'}}
              </template>
            </el-table-column>
            <el-table-column prop="roleDescription" label="角色描述">
            </el-table-column>
            <el-table-column label="创建时间" width="160" prop="createTime">
            </el-table-column>
            <el-table-column prop="" label="操作" width="280">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" style="color: #fff; width: 75px"
                  @click="handleClick(scope.row), (Modifythe = true)">修改
                </el-button>
                <el-popconfirm title="确定执行该操作吗?" @confirm="modifybanksrepeat">
                  <el-button size="mini" style="background-color: #ff0000;
                      color: #fff;margin:0 0 0 10px" slot="reference" @click="handleDelete( scope.row)">
                    {{ scope.row.roleStatus=='yes'?'停用' :'启用'}}</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <div class="block">
            <el-pagination :current-page="formInline.pageNum" :page-size="formInline.pageSize"
              :page-sizes="[10, 20, 30]" @current-change="handleCurrentChange" @size-change="handleSizeChange"
              layout="total,prev, pager, next, sizes" :total="total">
            </el-pagination>
          </div>
        </div>
        <!-- 新增 -->
        <el-dialog title="系统管理-新增角色" :visible.sync="newrole" :close-on-click-modal="false" width="40%">
          <div class="header-1">
            <div class="header-1-1-1">
              <div class="tou"></div>
              <span>新增角色</span>
            </div>
          </div>
          <el-form size="mini" :data="Queryrole" :model="addrole" status-icon :rules="addrole" ref="addrole"
            label-width="100px" class="demo-ruleForm">
            <div class="form_item">
              <el-form-item label="角色名称：" prop="positionName">
                <el-input style="width: 350px" v-model="addrole.positionName">
                </el-input>
              </el-form-item>
            </div>
            <div class="form_item">
              <el-form-item label="角色描述：" prop="positionDesc">
                <el-input style="width: 350px" v-model="addrole.positionDesc">
                </el-input>
              </el-form-item>
            </div>
            <el-form-item label="菜单设置：">
              <!-- <el-cascader
                style="width: 350px"
                :options="permissionsList"
                :props="Settings"
                collapse-tags
                clearable
                @change="XzhandleSubCatCd"
                ref="myCascader"
              >
              </el-cascader> -->
              <!-- @check-change="aaaaa"current-node-key -->

              <el-tree @check="addtreechange"  :data="menuList" show-checkbox :default-expand-all="false" node-key="id"
                ref="tree" highlight-current :props="defaultPropsa">
              </el-tree>
            </el-form-item>
            <!-- <el-form-item label="权限设置：">
             
              <el-tree @check="addtreepermissionschange" :default-checked-keys='revise.permissions'
                :data="PrivilegeList" show-checkbox :default-expand-all="false" node-key="value" ref="tree"
                highlight-current :props="defaultPropsapermissions">
              </el-tree>
            </el-form-item> -->
            <el-button type="primary" @click="roleadd">确认</el-button>
            <el-button type="primary" @click="newrole=false">取消</el-button>
          </el-form>
        </el-dialog>
        <!-- 修改 -->
        <el-dialog title="系统管理-修改角色" :visible.sync="Modifythe" :close-on-click-modal="false" width="40%">
          <div class="header-1">
            <div class="header-1-1-1">
              <div class="tou"></div>
              <span>修改角色</span>
            </div>
          </div>
          <el-form size="mini" :data="Queryrole" :model="revise" status-icon :rules="revise" ref="revise"
            label-width="100px" class="demo-ruleForm">
            <div class="form_item">
              <el-form-item label="角色名称：" prop="positionName">
                <el-input style="width: 350px" v-model="revise.positionName">
                </el-input>
              </el-form-item>
            </div>
            <div class="form_item">
              <el-form-item label="角色描述：" prop="positionDesc">
                <el-input style="width: 350px" v-model="revise.positionDesc">
                </el-input>
              </el-form-item>
            </div>
            <!--  -->
            <el-form-item label="菜单设置：">
              
              <el-tree @check="edittreechange"  :default-checked-keys='revisemenusList' :data="menuList" show-checkbox
                :default-expand-all="false" node-key="id"  ref="tree" highlight-current :props="defaultPropsa">
              </el-tree>
            </el-form-item>
            <!-- 权限设置 -->
            <!-- <el-form-item label="权限设置：">
              <el-tree @check="edittreepermissionschange" :default-checked-keys='revise.permissions'
                :data="PrivilegeList" show-checkbox :default-expand-all="false" node-key="value" ref="tree"
                highlight-current :props="defaultPropsapermissions">
              </el-tree>
            </el-form-item> -->
            <el-button type="primary" @click="geteeedit">确认</el-button>
            <el-button type="primary" @click="Modifythe=false">取消</el-button>
          </el-form>
        </el-dialog>
      </div>
    </div>

  </div>
</template>
<script>
  export default {
    name: "position",
    data() {
      return {
        defaultPropsa: {
          children: 'chirl',
          label: 'menuName'
        },
        defaultPropsapermissions: {

          label: 'label'
        },
        pageSize: 10,
        pageNum: 1,
        enableStart: "",
        dfghsgfsg: [{
          status: "deactivate"
        }],
        positionId: 0,
        // 日期
        CX: {
          date1: new Date(new Date() - (3600 * 1000 * 24 * 7 + 1000)).toLocaleDateString().replace(/\//g, "-"), // 日期时间
          date2:  new Date(new Date().getTime() +86400000).toLocaleDateString().replace(/\//g, "-"),
        },
        // 权限
        value: [],
        PrivilegeList: [{
            value: 1,
            label: "浏览",
          },
          {
            value: 2,
            label: "修改",
          },
          {
            value: 4,
            label: "删除",
          },
          {
            value: 8,
            label: "提交（或申请）",
          },
          {
            value: 16,
            label: "审核（或其他）",
          },
        ],
        permissionsList: [],
        permissions: [],
        permissionsqc: [],
        menus: [],
        permissionsValue: [],
        Settings: {
          multiple: true,
          expandTrigger: "hover"
        },
        defaultProps: {
          children: "chirden",
          label: "label",
          value: "menuId",
        },
        newrole: false,
        Modifythe: false,
        currentPage: 1,
        total: 0, // 多少条数据
        formInline: "",
        menuList: [],
        // 新增角色
        addrole: {
          positionName: "",
          positionDesc: "",
          permissions: [],
          permissionstree: [],
          menus: [],
        },
        // 查询角色
        Queryrole: {
          pageNum: 1,
          pageSize: 10,
          positionName: "",
          positionDesc: "",
          updateTime: "",
          status: '',
        },
        // 修改角色
        revise: {
          positionId: "",
          positionName: "",
          positionDesc: "",
          menus: [],
          permissions: [],
        },
        // 角色列表
        Therolelist: [],
        // xiugai角色
        revisemenusList:[],
        revisemenusLists:[]
      };
    },
    methods: {
      

      // 角色状态
      handleDelete(row) {
        console.log(row)
        this.positionId = row.id
        this.enableStart = row.roleStatus
      },
      // 状态成功的回调
      modifybanksrepeat() {
        this.$axios.geteeedit({
          id: String(this.positionId),
          status: this.enableStart == "no" ? "yes" : "no"
        }).then((res) => {
          if (res.code == "00000") {
            this.$message({
              message: '操作成功',
              type: 'success'
            });
            this.getrolealist();
          }
        })
      },
      addtreechange(checkedNodes, checkedKeys) {
        // console.log(checkedNodes, checkedKeys);
        console.log(checkedNodes,checkedKeys);
        let arr =   checkedKeys.checkedKeys.concat(checkedKeys.halfCheckedKeys)
          this.addrole.permissionstree = arr.map((item) => {
            return{id:item}
        });
        console.log(checkedKeys.checkedKeys,  this.addrole.permissionstree);
        // 获取value值
      },
      edittreechange(checkedNodes, checkedKeys) {
        console.log(checkedNodes, checkedKeys);
        let arr = checkedKeys.checkedKeys.concat(checkedKeys.halfCheckedKeys)
        console.log(arr)
         this.revisemenusLists =arr
        // 获取value值
        // this.revise.menus = checkedKeys.checkedKeys.map((item) => {
        //     return{id:item}
        // });;
      },
      edittreepermissionschange(checkedNodes, checkedKeys) {
        console.log(checkedNodes, checkedKeys);
        // 获取value值
        this.revise.permissions = checkedKeys.checkedKeys

      },
      addtreepermissionschange(checkedNodes, checkedKeys) {
        console.log(checkedNodes, checkedKeys);
        // 获取value值
        this.addrole.menus = checkedKeys.checkedKeys
      },
      XzhandleSubCatQx(value) {
        console.log("22", value);
        // 获取value值
        this.addrole.menus = value
          .toString()
          .split(",")
          .map(function (ele) {
            return +ele;
          });
        // console.log('qx',this.addrole.menus);
      },
      //     ddddd(){
      // this.permission();
      // console.log(this.data)

      //     },
      permission() {
        console.log(this.addrole.permissions);
        for (var i = 0; i < this.addrole.permissions.length; i++) {
          let dataArr = this.addrole.permissions[i];
          for (var j = 0; j < dataArr.length; j++) {
            this.permissions.push(dataArr[j]);
          }
        }
        let arr = this.permissions;
        let resultarr = [...new Set(arr)];
        this.addrole.permissions = resultarr;
        console.log(this.addrole.permissions);
      },
     
      handleCascaderInvoice(val) {
        console.log(val)
      },
      // 重置
      reset() {
        // this.formInline.deptId =""
      },
      seachBtn() {
        localStorage.setItem("pageSize", 10);
        localStorage.setItem("pageNum", 1);
        this.getrolealist()
      },
      //分页
      handleSizeChange(value) {
        console.log("1", value);
        localStorage.setItem("pageSize", value);
        localStorage.setItem("pageNum", 1);
        this.getrolealist();
        this.pageSize = value;  
      },
      handleCurrentChange(value) {
        console.log("2", value);

        localStorage.setItem("pageNum", value);
        localStorage.setItem("pageSize", this.pageSize);
        this.getrolealist();
        this.pageNum = value; 
        // orders = res.data;
      },
      // 添加角色
      roleadd() {
        if (this.addrole.positionName == "") {
          this.$confirm('角色名称不能为空', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        } else if (this.addrole.positionDesc == "") {
          this.$confirm('角色描述不能为空', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        } else if (this.addrole.permissionstree == "") {
          this.$confirm('菜单设置不能为空', '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
        } else {
          // this.permission();

          // 确定后关闭弹窗

          this.$axios
            .getroleadd({
              roleName: this.addrole.positionName,
              roleDescription: this.addrole.positionDesc,
              sysMenuBOList: this.addrole.permissionstree,
              // permissions: this.addrole.menus,
            })
            .then((res) => {
              console.log(res);
              if (res.code == "00000") {
                this.getqueryMenuAll()
                this.getrolealist();
                this.$message({
                  message: '新增成功',
                  type: 'success'
                });
                // this.addrole={}
                this.newrole = false;
              }
            });
        }
      },
      // 重置按钮
      clear() {
        this.Queryrole.positionName = '',
          this.Queryrole.positionDesc = '',
          this.Queryrole.menus = '',
          this.Queryrole.permissions = ''
        this.Queryrole.status = "",

          this.getrolealist();

      },


      // 所有菜单
      getqueryMenuAll() {
        this.$axios.getqueryMenuAll({}).then((res) => {
          console.log(res);
          if (res.code == "00000") {
          console.log(res);
          let arrpri = []
          for (let i = 0; i < res.data.length; i++) {
           
            if(res.data[i].menuPid == null){
              res.data[i].chirl = []
              arrpri.push(res.data[i])
            }
          }
          console.log(arrpri)
          for (let i = 0; i < arrpri.length; i++) {
            let node = {}
            for (let j = 0; j < res.data.length; j++) {
              if(arrpri[i].id ==res.data[j].menuPid&&res.data[j].menuPid!=null){
                arrpri[i].chirl.push(res.data[j])
              }
            }
          }
              
            this.menuList=arrpri







          //    console.log(arrpri);


            // this.menuList = res.data
            // console.log( this.menuList)
            // let list = JSON.parse(JSON.stringify(res.data));
            // // 数据循环
            // for (let index = 0; index < list.length; index++) {
            //   let node = {};
            //   node.value = list[index].menuId;
            //   node.label = list[index].menuName;
            //   node.children = [];
            //   for (let i = 0; i < list[index].ch.length; i++) {
            //     let node2 = {};
            //     node2.value = list[index].ch[i].menuId;
            //     node2.label = list[index].ch[i].menuName;
            //     node2.children = [];
            //     for (let j = 0; j < list[index].ch[i].ch.length; j++) {
            //       let node3 = {};
            //       node3.value = list[index].ch[i].ch[j].menuId;
            //       node3.label = list[index].ch[i].ch[j].menuName;
            //       node2.children.push(node3);
            //     }
            //     node.children.push(node2);
            //   }
            //   this.permissionsList.push(node);
            // }

         
            console.log(this.permissionsList);
          }
        });
      },
      // 查询角色
      getrolealist() {
        this.$axios
          .getrolealist({
            pageNo: this.pageNum,
            pageSize: this.pageSize,
            roleName: this.Queryrole.positionName,
            roleDescription: this.Queryrole.positionDesc,
            // Queryrole.status
          })
          .then((res) => {
            console.log(res);
            if (res.code == "00000") {
              // console.log(res.data.length, '--length')
              if (res.data.records.length < 1) {
                 this.$message({
                  message: "未查询到数据",
                  type: "warning",
                });
              }
              // 角色列表数据
              this.Therolelist = res.data.records;
              // 分页条数
              this.total = res.data.total;
            }
          });
      },

      handleClick(row) {
        console.log(row)
        console.log(this.menuList)
        // this.$nextTick(() => {
        //     this.$refs.tree.setCheckedKeys([]);
        //  });
        console.log(this.menuList)
         this.$axios
          .getRoleInfo({
           id:String(row.id)
          })
          .then((res) => {
            console.log(res);
            if(res.code == "00000"){
               this.revise.positionId = res.data.id;
                this.revise.positionDesc = res.data.roleDescription;
                this.revise.positionName = res.data.roleName;
                let positionMenuList =res.data.sysMenuBOList
                let positionMenuList1 =res.data.sysMenuBOList
                let arr1 = []
            for (let i = 0; i < positionMenuList1.length; i++) {
              arr1.push(positionMenuList1[i].id)
            }
            this.revise.menus = arr1
            positionMenuList = positionMenuList.filter((item)=>{
              return item.menuPid !=null
            })
            console.log(positionMenuList)
            let arr = []
            for (let i = 0; i < positionMenuList.length; i++) {
              arr.push(positionMenuList[i].id)
            }
            console.log(arr)
              this.revisemenusList  = arr
            }
          });
      },
      // 修改角色
      geteeedit() {
        console.log(this.revisemenusLists.length)
        if(this.revisemenusLists.length == 0){
          this.revise.menus = this.revise.menus.map((item) => {
                    return{id:item}
                });
        }else{
          this.revise.menus = this.revisemenusLists.map((item) => {
                    return{id:item}
                });
        }
        if (
          this.revise.menus != "" &&
          this.revise.positionName != "" &&
          this.revise.positionDesc != ""
        ) {
          console.log(this.revise)
          // 确定后关闭弹窗
          this.$axios
            .geteeedit({
              id: this.revise.positionId,
              roleName: this.revise.positionName,
              roleDescription: this.revise.positionDesc,
              sysMenuBOList: this.revise.menus,
            })
            .then((res) => {
              console.log(res);
              if (res.code == "00000") {
          this.Modifythe = false;

                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
                this.getrolealist();
              }
            });
        } else {
          this.$message({
            message: '请认真填写信息，所有选项均为必填项',
            type: 'warning'
          });
        }
      },
    },
    mounted() {
      // this.roleadd();
      this.getqueryMenuAll();
      // 查询角色
      this.getrolealist();
    },
  };
</script>
<style scoped>
  .position {
    height: 100%;
    background-color: #f7f7f7;
    padding-bottom: 70px;
  }

  .form_item {
    display: flex;
  }

  .header-1-1 {
    font-weight: bolder;
    display: flex;
    margin-left: 20px;
    padding-top: 20px;
  }

  .header-1-1-1 {
    font-weight: bolder;
    display: flex;
    margin-left: 20px;
  }

  .tou {
    width: 3.5px;
    height: 17px;
    background-color: #4b71bf;
    margin-top: 2px;
    margin-right: 4px;
    font-size: 12px;
    margin-bottom: 25px;
  }

  .tuo {
    font-weight: bolder;
    display: flex;
    margin-left: 20px;
    padding-top: 20px;
    justify-content: space-between;
    margin-right: 20px;
  }

  .tuo-1 {
    display: flex;
  }

  .tuo-2 {
    width: 3.5px;
    height: 17px;
    background-color: #4b71bf;
    margin-top: 2px;
    margin-right: 4px;
    font-size: 12px;
    margin-bottom: 25px;
  }

  .invoice-9 {
    font-size: 11px;
  }

  .invoice {
    width: 97%;
    margin: auto;
    display: flex;
    height: 44px;
    margin-bottom: 20px;
    min-width: 1200px;
  }

  .invoice-1 {
    margin-right: 20px;
  }

  .invoice-2 {
    margin-left: 20px;
  }

  .hackhome {
    border-top: 1px solid #e0e0e0;
    width: 98%;
    margin-left: 20px;
  }

  .table {
    margin-left: 20px;
    margin-right: 20px;
  }

  .top-6 {
    display: flex;
  }

  .tou-3 {
    display: flex;
  }

  #selectForm>>>.el-form-item__label {
    font-size: 11px;
  }

  .pop-9 {
    font-size: 11px;
    width: 120px;
    padding-top: 5px;
  }

  .pop {
    margin-left: 20px;
  }

  .pop-1 {
    width: 400px;
  }

  .pop-1-2 {
    display: flex;
    margin-bottom: 20px;
  }

  .pop-3 {
    margin-left: 20px;
    margin-top: 40px;
  }

  .form {
    margin-left: 20px;
  }

  .cell {
    display: flex;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 80px;
    height: 80px;
    display: block;
    margin-left: 20px;
    border-radius: 50%;
    margin-bottom: 20px;
    background-color: #d9d9d9;
  }

  .upload {
    margin-left: 25px;
    font-size: 12px;
    margin-bottom: 5px;
    margin-top: 32px;
  }

  .upload_box {
    display: flex;
  }

  .block {
    margin-left: 20px;
    padding-bottom: 20px;
    margin-top: 10px;
    float: right;
  }
</style>